﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.InteropServices;
using MINERP.COM;
using System.Diagnostics;
using System.Threading;
using System.Configuration;
using System.Net.Sockets;
using System.Text;

namespace MINERP.UserLogin
{
    static class StartUP
    {
        private static FrmUpdate _frmUpdate = null;     //用于显示的等待信息的窗体
        private static string strSendMsg = "GM|";       //用于向服务器发送请求信息
        private const int CONNECTTIMEOUT = 2000;        //连接服务器的超时时间
        private static string strConnectionString;      //连建字符串
        private static string strComputerNameAndIp;     //服务器的名字和IP
        private static string strVersion;               //版本号
        private static string strNewSetpPath;           //最新版本的安装地址
        private static string ServerIP;                 //服务器的IP
        private static int ServerPort;                  //服务器的端口
        private delegate int ConnectServerDelegate();   //与数据库建接的DL


        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        //[STAThread]
        //static void Main()
        //{
        //    Application.EnableVisualStyles();
        //    Application.SetCompatibleTextRenderingDefault(false);

        //    bool bCreatedNew;
        //    Mutex m = new Mutex(false, "myUniqueNameaaaa", out bCreatedNew);

        //    if (bCreatedNew)
        //    {

        //        //ShowUpdateForm();
        //        //list = UDPMessage.GetServerInfo();
        //        //UpdateVersion();
        //        ConnectServerDelegate dlConn = ConnectServerAndGetMsg;

        //        IAsyncResult dr = dlConn.BeginInvoke(null, null);
        //        while (!dr.IsCompleted)
        //        {
        //            Thread.Sleep(10);
        //        }
        //        int result = dlConn.EndInvoke(dr);

        //        //_frmUpdate.Close();

        //        if (result == 1)
        //        { 
        //            string curVersion = GetCurrentVersion();

        //            if (string.IsNullOrEmpty(strVersion) || strVersion == curVersion)
        //            {
        //                Application.Run(new FrmLogin(strComputerNameAndIp));
        //            }
        //            else
        //            {                       
        //                Process.Start(strNewSetpPath);//执行安装
        //                Application.Exit();
        //            }                   
        //        }
        //        else
        //        {
        //            MessageBox.Show(string.Format("与服务器{0}连接异常，程序即将退出！请联系管理员！", ServerIP));
        //        }
                
        //    }

        //}
        //显示等待信息
        static void ShowUpdateForm()
        {
            _frmUpdate = new FrmUpdate();
            _frmUpdate.ShowInTaskbar = false;
            _frmUpdate.Show();
        }



        //得到当前的版本
        static string GetCurrentVersion()
        {
            string version = string.Empty;
            for (int i = 0; i < Assembly.GetExecutingAssembly().GetCustomAttributes(true).Length; i++)
            {
                if (Assembly.GetExecutingAssembly().GetCustomAttributes(true)[i] is AssemblyFileVersionAttribute)
                {
                    version = ((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(true)[i]).Version;
                }
            }
            return version;
        }

        //联连服务器得到相关的信息
        private static int ConnectServerAndGetMsg()
        {
            int result = -1;
            byte[] myReadBuffer = new byte[5120];
            ServerIP = ConfigurationManager.AppSettings["RemoteIP"].ToString();
            ServerPort = Convert.ToInt32(ConfigurationManager.AppSettings["RemotePort"]);


            string RedStrResult;
            TcpClient client = new TcpClient();
            try
            {
                client.Connect(ServerIP, ServerPort);
                client.SendTimeout = CONNECTTIMEOUT;
                NetworkStream net = client.GetStream();

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(strSendMsg);

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);

                while (true)
                {
                    int redLenth = -1;//得取得的字符串长度
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        result = -2;//从服务器获得数据出错
                        break;
                    }

                    if (redLenth > 0)
                    {
                        RedStrResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        result = 1;//成功
                        break;
                    }
                }
                net.Close();

            }
            catch (Exception)
            {
                result = -1;//建接服务器出错
            }
            finally
            {
                client.Close();
            }

            return result;
        }

        //解析从服务器得到的字符串
        private static void ProcessStrMsg(string strMsg)
        {
            strConnectionString = strMsg.Split('|')[0].ToString();   //连建字符串
            strComputerNameAndIp = strMsg.Split('|')[1].ToString();  //服务器的名字和IP
            strVersion = strMsg.Split('|')[2].ToString();            //版本号
            strNewSetpPath = strMsg.Split('|')[3].ToString();        //最新版本的安装地址
        }

        #region old
        //检查版本是否相同
        //static void UpdateVersion()
        //{
        //    string currentVersion = GetCurrentVersion();
        //    string messageStr = list[0];
        //    string[] str = messageStr.Split('|');
        //    string newVersion = str[2];
        //    string updateFilePath = str[3];
        //    CloseUpdateForm();
        //    if (currentVersion != newVersion)
        //    {
        //        if (MessageBox.Show("程序检测到新版本，您需要更新吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
        //        {
        //            Process.Start(updateFilePath);
        //            Exit();
        //        }
        //    }
        //}

        //static void KillEMProcess()//关闭所有正在运行的进程
        //{
        //    System.Diagnostics.Process[] pTemp = System.Diagnostics.Process.GetProcesses();
        //    foreach (System.Diagnostics.Process pTempProcess in pTemp)
        //    {

        //        if ((pTempProcess.ProcessName.ToLower() == ("MINERP.UserLogin").ToLower()) || (pTempProcess.ProcessName.ToLower()) == ("MINERP.UserLogin.exe").ToLower())
        //            pTempProcess.Kill();
        //    }
        //}


        //static void CloseUpdateForm()
        //{
        //    _frmUpdate.Close();
        //}

        //static void Exit()
        //{
        //    KillEMProcess();
        //    Environment.Exit(0);
        //}

        #endregion
    }
}
